<template>
	<view>
		<!-- 启动遮罩 -->
		<!-- <u-overlay :show="passValue" :mask-click-able="false" :opacity="0.2">
			<view class="warp" style="display: flex;justify-content: center;align-items: center;margin-top: 39vh;">
				<view style="width: 130px;height: 130px;background-color: #000;border-radius: 10px;display: flex;align-items: center;justify-content: center;opacity:0.7">
					<u-loading-icon mode="semicircle" size="60" color="#FFF" :vertical="true" text="正在加载" textColor="#FFF"></u-loading-icon>
				</view>
			</view>
		</u-overlay> -->
		<view class="topNav">
			<view @click="reverseLayerList"
				style="background-color: rgba(255, 80, 0, 0.85); border-radius: 4px;padding: 4px;margin-right: 10px;">
				<u-icon color="white" bold name="list" size="19"></u-icon>
			</view>
			<u-search placeholder="项目名称" v-model="queryParam.xmmc" :showAction="false" style="" bgColor="#FFFFFF"
				borderColor=" rgba(255, 80, 0, 0.85)" @change="search" @focus="showQueryH=true"></u-search>
		</view>

		<view v-show="showQueryH" id="one" :onscroll="checkScroll()">
			<div style="height: 44px;"></div>
			<scroll-view :style="getHeight()" scroll-y="true">
				<view class="noSearch" v-show="queryList.length==0">
					<div style="height: 100px;"></div>
					<u-empty mode="search" text="暂无数据" @click.native="showQueryH=false"></u-empty>
				</view>
				<u-list :lowerThreshold="1" @scrolltolower="scrolltolowerS()">
					<u-list-item v-for="(item, index) in queryList" :key="index">
						<u-cell customStyle="padding-Left: 20rpx" :title="item.xmmc + ' - ' + item.facilities_type"
							@click="handClickFacility(item)">
						</u-cell>
					</u-list-item>
				</u-list>
			</scroll-view>
		</view>

		<view class="map" id="two">
			<comp-map v-if="showMapComp" ref="mainMap" :showSwitchBtn="true" text="1" @mapMounted="onMapMpunted"
				@pointClick="onPointClick" @switchClick="switchList" />
		</view>

		<u-popup :show="showLayerList" mode="left" overlayOpacity="0.5" :closeOnClickOverlay="true"
			:customStyle="layerListStyle" @close="closeLayerList">
			<view>
				<u-list customStyle="width:80vw">
					<u-list-item v-for="(item, index) in layerList" :key="index">
						<u-cell :title="item.name" @click="handClickLayer(item)" :value="item.lengthZZZ==0? '0' : item.lengthZZZ">
							<u-icon slot="right-icon" name="checkmark" color="#FF5000" size="20"
								v-if="item.name===currentLayer.name"></u-icon>
							<u-icon slot="right-icon" name="checkmark" color="#FFF" size="20"
								v-if="item.name!==currentLayer.name"></u-icon>
						</u-cell>
					</u-list-item>
				</u-list>
			</view>
		</u-popup>
		<!-- 详情 -->
		<u-popup :show="showFullView" height="300px" mode="bottom" @close="closePopup">
			<view style="height: 280px;display: flex;flex-direction: column;">
				<view class="top"
					style="display:flex;justify-content: space-between;margin: 5px 16px;align-items: center;">
					<view class="left">{{popupTitle}}</view>
					<view class="right" style="display: flex;align-items: center;">
						<u-button customStyle='height:30px;width:90px' type="primary" :plain="true"
							@click="showDetailedInfo">详细信息</u-button>
						<u-button customStyle='height:30px;margin-left:10px;width:60px' :plain="true" color="#FF5000"
							@click="showLocationPop">导 航</u-button>
					</view>
				</view>
				<div><u-line></u-line></div>
				<view style="flex: 1;">
					<u-swiper :list="imgList" :height="242"></u-swiper>
				</view>
			</view>
		</u-popup>
		<!-- 导航 -->
		<u-popup :show="showLocation" height="200px" mode="bottom" @close="closePopupLocation" round="10">
			<view>
				<view class="title" style="margin: 10px;">
					请选择
				</view>
				<view class="baidu" @click="gotoBaidu" style="display: flex;align-items: center;justify-content: space-between;padding: 10px;">
					<view class="baidu_left" style="display: flex;align-items: center;">
						<view class="baidu_icon" style="height: 32px;width: 32px;border: 2px solid #c8c9cc;border-radius: 4px;">
							<u--image :src="baiduIcon" width="32px" height="32px"></u--image>
						</view>
						<view style="margin-left: 20px;">百度地图</view>
					</view>
					<view class="baidu_right">
						<u--image :src="gotoIcon" width="22px"
						    height="22px"
						  ></u--image>
					</view>
				</view>
				<view class="gaode" @click="gotoGaode" style="display: flex;align-items: center;justify-content: space-between;padding: 10px;margin-bottom: 20px;">
					<view class="gaode_left" style="display: flex;align-items: center;">
						<view class="gaode_icon" style="height: 32px;width: 32px;border: 2px solid #c8c9cc;border-radius: 4px;">
							<u--image :src="gaodeIcon" width="32px" height="32px"></u--image>
						</view>
						<view style="margin-left: 20px;">高德地图</view>
					</view>
					<view class="gaode_right">
						<u--image :src="gotoIcon" width="22px"
						    height="22px"
						  ></u--image>
					</view>
				</view>
			</view>
		</u-popup>
		
		<!-- 消息 -->
		<u-modal 
			:show="showMessage" 
			:title="titleMessage" 
			:content="contentMessage"
			confirmText="确 认"
			cancelText="关 闭"
			showCancelButton
			confirmColor="#FF5500"
			closeOnClickOverlay
			@confirm="sendMessage"
			@cancel="showMessage = false"
			@close="showMessage = false"
		>
			<view class="messageContainer" style="max-height: 50vh;overflow-y: auto;">
				<view class="messages" v-for="(zoo,indexms) in messageList" :key="indexms">
					<view class="zoos">
						{{ '' + (indexms + 1) + '、' + zoo.nr }}
					</view>
				</view>
			</view>
		</u-modal>

	</view>
</template>

<script>
	import croods from '@/common/croods-1.3.3.js';
	window.croods = croods;
	window.hydra = require('../../common/wst_hydra-1.0.0.js');




	import coordtransform from 'coordtransform';
	import compMap from "@/components/comp-map/comp-map.vue"
	import { wgs84ToGcj02, wgs84ToBd09 } from '@/common/coordinateUtils.js'
	import {
		getToken,
		getDictionaryData,
		getFacilityList,
		queryFacility,
		getFacilityListByXmmc,
		getXcMessage,
		sendXcMessage
	} from '@/common/api.js';
	import {
		mapState
	} from 'vuex';
	import {
		nextTick
	} from "vue";
	import toast from '../../uni_modules/uview-ui/libs/config/props/toast.js';
	export default {
		components: {
			compMap
		},
		computed: {
			...mapState(['loginStatus', 'isLogin', 'loginMsg','oneShowStatus']),
		},
		onLoad: function() {},
		onShow() {
			/* if(this.test){                                   
				document.body.style.overflow = 'hidden';
				this.updateMap();
			} */
			this.showQueryH = false
			this.showMapComp = true;
			/* let that = this
			this.$nextTick(() => {
				that.showMapComp = true;
			}) */
		},
		onHide() {
			this.showMapComp = false;
		},
    watch: {
      loginStatus(status) {
        if(status) {
          this.getMessage()
          this.initData()
          this.updateMap()
        }
      }
    },
		data() {
			return {
				passValue: true,
				statusLoading: false,
				showFullView: false,
				showLayerList: false,
				popupTitle: "",
				showQueryH: false,
				imgList: [],
				selectPointId: null,
				currentLayer: {
					name: '全部',
					id: ''
				},
				layerList: [{
					name: '全部',
					id: ''
				}], //查询的list
				layerListStyle: {
					marginTop: "54px",
					width: "80vw"
				},
				queryParam: {
					pageNum: 1,
					pageSize: 20,
					facilities_type: null,
					xmmc: ""
				},
				queryList: [],
				disList: [],
				tabBarHeight: 0,
				showMapComp: true,
				isOver: false,
				
				
				tempData:null,
				showLocation:false,
				baiduIcon:require("@/static/assets/baidu.png"),
				gaodeIcon:require("@/static/assets/gaode.png"),
				gotoIcon:require("@/static/assets/goto.png"),
				
				contentMessage:"xxx",
				titleMessage:"巡检任务通知",
				showMessage:false,
				messageList:[]
			}
		},
		async mounted() {},
		methods: {
			getMessage(){
				if(this.oneShowStatus){
					getXcMessage().then(res => {
						if(res.length!=0){
							this.messageList = res
							this.showMessage = true
							this.$store.commit('changeShowStatus',false)
						}
					})
				}
			},
			sendMessage(){
				this.showMessage = false
				if(this.messageList.length > 0){
					const idString = this.messageList.map(item => item.id).join(',')
					sendXcMessage({ids:idString}).then(res => {
						if(res > 0){
							uni.$u.toast('确认成功')
						}
					})
				}
			},
			checkScroll() {
				let view2 = document.getElementById('one');
				if (view2 && view2.scrollTop + view2.clientHeight >= view2.scrollHeight) {
					document.body.style.overflow = 'hidden';
				} else {
					document.body.style.overflow = 'auto';
				}
			},
			
			async getListData() {
				try {
					let that = this
					let result = await getFacilityListByXmmc(that.queryParam)
					that.isOver = result.nextPage == 0 ? true : false
					let data = result.list
					data.forEach(item => {
						let temps = that.disList.find(dict => dict.id === item.facilities_type)
						if (temps) {
							item.facilities_type = temps.name
						}
					})
					that.queryList = data
				} catch (e) {
					/* console.log(e); */
				}
			},
			async initData() {
				try {
					let that = this
					let res = await getDictionaryData({
						status: "Enabled",
						type: "SPONGE_FACILITY_TYPE"
					})
					that.disList = res
					res.forEach(item => {
						let temp = that.layerList.find(zoo => zoo.code == item.code)
						if (!temp) {
							that.layerList.push(item)
						}
					})
					/* that.layerList = that.layerList.concat(res) */

					/* 格式化请求参数 */
					that.queryParam = {
						pageNum: 1,
						pageSize: 20,
						facilities_type: null,
						xmmc: ""
					}
					await that.getListData()
				} catch (error) {
					/* console.error(error); */
				}
			},
			async search() {
				try {
					let that = this
					/* 更新请求参数 */
					that.queryParam.pageNum = 1
					that.queryParam.pageSize = 20
					await that.getListData()
				} catch (error) {
					/* console.error(error); */
				}
			},

			/* 鉴权初始化 */
			async onMapMpunted(status) {
				let that = this
				/* if(!that.isLogin){
					uni.reLaunch({
						url:'/pages/login/index'
					})
				} */
        if (!that.loginStatus) {
          if (that.loginMsg != '') {
            uni.$u.toast(that.loginMsg)
          }
        } else {
          that.getMessage()
          that.initData()
          that.updateMap()
        }


				/* if(!sessionStorage.getItem('wuhu-sponge-key')){
					window.croods.customPlugin({
						action: "UserPlugin.login", 
						params: {},
						success: function(res) {
							alert(JSON.stringify(res))
							getToken({wstoken:res.token}).then(response => {
								if(response.msgCode=="200"){
									sessionStorage.setItem('wuhu-sponge-key','118E37102P-31N36162P-PASS')
									that.initData()
									that.updateMap()
									that.passValue = false
								}else{
									sessionStorage.setItem('wuhu-sponge-key','118E37102P-31N36162P-FAIL')
									that.passValue = false
									that.$u.toast(response.msgCode)
								}
							})
						}
					})
				}else{
					if(sessionStorage.getItem('wuhu-sponge-key')=='118E37102P-31N36162P-PASS'){
						that.initData()
						that.updateMap()
						that.passValue = false
					}else{
						that.passValue = false
					}
				} */
			},
			async onPointClick(event) {
				let that = this;
				try {
					let res = await queryFacility(event.id);
					that.selectPointId = event.id;
					that.tempData = res
					if (res.projectFacilitiesZpDtoList != null &&
						res.projectFacilitiesZpDtoList.length > 0) {
						that.imgList = res.projectFacilitiesZpDtoList.map(item => {
							return item.zpzsdz;
						})
					} else {
						that.imgList = []
					}
					if (that.imgList.length == 0) {
						that.imgList.push("/static/icons/no_all_full_img.png")
					}
					that.popupTitle = "设施 - " + res.facilities_type_name;
					that.showFullView = true;
				} catch (error) {
					// 处理请求失败的逻辑
					/* console.error(error); */
				}
			},
			showLocationPop(){
				if(this.tempData.xmmc && this.tempData.lng && this.tempData.lat){
					this.showLocation = true
				}else{
					uni.$u.toast("当前设施信息缺失无法前往导航")
				}
			},
			closePopupLocation(){
				this.showLocation = false
			},
			gotoBaidu(){
				const [bdLng, bdLat] = wgs84ToBd09(this.tempData.lng,this.tempData.lat)
				let temp = `name:${this.tempData.xmmc}|latlng:${bdLat},${bdLng}`
				croods.customPlugin({
					action: 'CustomJumpPlugin.goBaiduMap',
					params: {
						destination:temp,
					},
					success: function () {
						
					},
					fail: function (msg) {
					}
				});
			},
			gotoGaode(){
				const [gcjLng, gcjLat] = wgs84ToGcj02(this.tempData.lng,this.tempData.lat)
				let temp = `&dlat=${gcjLat}&dlon=${gcjLng}&dname=${this.tempData.xmmc}`
				croods.customPlugin({
					action: 'CustomJumpPlugin.goGaoDeMap',
					params: {
						destination:temp,
					},
					success: function () {
						
					},
					fail: function (msg) {
					}
				});
			},
			closePopup() {
				this.showFullView = false;
			},
			showDetailedInfo() {
				uni.$u.route({
					url: `/pages/hmss/ssxq/index?id=${this.selectPointId}`
				});
			},
			closeLayerList() {
				this.showLayerList = false;
			},
			reverseLayerList() {
				this.showLayerList = !this.showLayerList
			},

			async handClickLayer(item) {
				let that = this;
				that.reverseLayerList();
				
				/* 更正请求参数 */
				that.queryParam.pageNum = 1
				that.queryParam.pageSize = 20
				that.currentLayer = item;
				if (that.currentLayer.name === "全部") {
					that.queryParam.facilities_type = null
				} else {
					that.queryParam.facilities_type = item.id
				}
				await that.getListData()
				that.updateMap();
			},
			async handClickFacility(item) {
				try {
					let res = await queryFacility(item.id);
					if (res.lat == undefined || res.lng == undefined) {
						this.$u.toast('未查询到该项目坐标信息');
						return
					} else {
						const points = [
							[res.lat, res.lng]
						];
						this.$refs.mainMap.moveByPoints(points);
						this.showQueryH = false;
						this.queryParam.xmmc = '';
					}
				} catch (error) {
					/* console.error(error); */
				}
			},
			async updateMap() {
				let that = this;
				try {
					let res = await getFacilityList({});
					
					/*  执行计数方法  */
					let allCount = 0
					that.layerList.forEach(item => {
						if(item.name!="全部"){
							const datas = res[item.id]
							if(datas){
								item.lengthZZZ = datas.length
								allCount += datas.length
							}else{
								item.lengthZZZ = 0
							}
						}
					})
					that.layerList.find(item => {
						if(item.name == "全部"){
							item.lengthZZZ = allCount
						}
					})
					
					if (that.currentLayer.name == "全部") {
						let points = []
						for (let key in res) {
							points = points.concat(res[key])
						}
						points = points.filter(item => item.lng !== undefined && item.lng !== null && item.lat !==
							undefined && item.lat !== null);
						points = points.map(it => {
							it.icon = "ss_" + it.facilities_type
							return it
						})
						that.$refs.mainMap.addPointTolayer("设施", points);
					} else {
						let points = res[that.currentLayer.id]
						if (points == null) {
							points = []
						} else {
							points = points.filter(item => item.lng !== undefined && item.lng !== null && item.lat !==
								undefined && item.lat !== null);
							points = points.map(it => {
								it.icon = "ss_" + it.facilities_type
								return it
							})
						}
						that.$refs.mainMap.addPointTolayer("设施", points);
					}
				} catch (error) {
					// 处理请求失败的逻辑
					/* console.error(error); */
				}
			},
			switchList() {
				uni.$u.route({
					url: `/pages/hmss/sslb/index`
				});
			},
			getHeight() {
				let a = uni.getSystemInfoSync().windowHeight - 54 - 5
				return {
					'height': a + 'px',
					'margin-top': '10px',
				}
			},

			async scrolltolowerS() {
				if (this.isOver) {
					return
				} else {
					this.queryParam.pageNum += 1
					let listres = await getFacilityListByXmmc(this.queryParam);
					this.isOver = listres.nextPage == 0 ? true : false
					let data = []
					data = listres.list
					data.forEach(item => {
						let temps = this.disList.find(dict => dict.id === item.facilities_type)
						if (temps) {
							item.facilities_type = temps.name
						}
					})
					this.queryList = this.queryList.concat(data)
				}
			}
		}
	}
</script>

<style>
	page {
		height: 100%
	}

	.topNav {
		background: transparent;
		/* 将背景改成透明 */
		position: fixed;
		/* 浮动在页面顶部 */
		top: 10px;
		/* margin-top 10px */
		left: 15px;
		right: 15px;
		display: flex;
		/* 两个元素放在一行的位置水平对齐 */
		align-items: center;
		/* 两个元素放在一行的位置水平对齐 */
		z-index: 2000;
	}

	.map {
		position: relative;
		top: 30;
		z-index: 500;
		height: 100vh;
	}
</style>